package com.blackink.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class ShiroConfig {
    //shiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(
            @Qualifier("SecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        //shiro内置过滤器
        /*
            anon:无需认证就可访问
            authc:认证后访问
            user:点击“记住我”功能可访问
            perms:拥有权限才可以访问
            role:拥有某个角色才能访问
         */
        LinkedHashMap<String,String> filterMap = new LinkedHashMap<String,String>();
        filterMap.put("/*.js","anon");
        filterMap.put("/layer/**","anon");
        filterMap.put("/css/**","anon");
        filterMap.put("/assets/**","anon");
        filterMap.put("/images/**","anon");
        filterMap.put("/js/**","anon");
        filterMap.put("/laydate/**","anon");
        filterMap.put("/layui/**","anon");
        filterMap.put("/*.css","anon");
        filterMap.put("/index","authc");
        filterMap.put("/qqq","authc");
//        filterMap.put("/updow","authc");
        filterMap.put("/captcha/**","anon");
//        filterMap.put("/**","authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //登录拦截
        bean.setLoginUrl("/login");

        return bean;
    }

    //DefaultWebSecurityManager
    @Bean(name = "SecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm());
        return securityManager;
    }

    //自定义realm对象↓
    @Bean(name = "userRealm")
    public CustomRealm userRealm(){
        CustomRealm customRealm = new CustomRealm();
        customRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return customRealm;
    }

    /**
     * 密码加密算法设置
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(1);
        return hashedCredentialsMatcher;
    }
}
